package cn.kgc.service.impl;

import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.util.UserContextHolder;
import cn.kgc.constant.WmsPurchaseStatus;
import cn.kgc.dto.add.WmsPurchaseAddDTO;
import cn.kgc.dto.add.WmsPurchaseDetailAddDTO;
import cn.kgc.entity.WmsPurchaseDetail;
import cn.kgc.entity.WmsWareSku;
import cn.kgc.mapper.WmsPurchaseDetailMapper;
import cn.kgc.mapper.WmsWareSkuMapper;
import cn.kgc.service.WmsWareSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.mapper.WmsPurchaseMapper;
import cn.kgc.entity.WmsPurchase;
import cn.kgc.service.WmsPurchaseService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * 采购信息(WmsPurchase)表服务实现类
 *
 * @author makejava
 * @since 2022-12-07 11:06:16
 */
@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseMapper, WmsPurchase> implements WmsPurchaseService {

    @Resource
    private WmsPurchaseMapper wmsPurchaseMapper;
    @Resource
    private WmsPurchaseDetailMapper wmsPurchaseDetailMapper;
    @Resource
    private WmsWareSkuMapper wmsWareSkuMapper;

    @Override
    public boolean acceptWmsPurchase(long id) {
        //获得登录用户的Id
        //String userId=UserContextHolder.getInstance().getUserId();
        String userId="1";
        WmsPurchase wmsPurchase = wmsPurchaseMapper.selectById(id);
        if(wmsPurchase==null){
            throw new HttpException(40003,500);
        }
        // 1如果采购单是已经分配 可以接受采购单
        if (wmsPurchase.getStatus()!=WmsPurchaseStatus.ALLOCATION.getStatus()){
            throw new HttpException(40004,500);
        }
        String assigneeId=wmsPurchase.getAssigneeId()+"";
        // 2接收采购的人和分配的人是否是同一个人
        if (!userId.equals(assigneeId)){
            throw new HttpException(40005,500);
        }
        // 3更改状态
        wmsPurchase.setStatus(WmsPurchaseStatus.SHOPPING.getStatus());
        return wmsPurchaseMapper.updateById(wmsPurchase)>0;
    }

    @Transactional
    public boolean saveWmsPurchase(WmsPurchaseAddDTO wmsPurchaseAddDTO) {
        //1 新建采购单
        WmsPurchase wmsPurchase = new WmsPurchase();
        BeanUtils.copyProperties(wmsPurchaseAddDTO, wmsPurchase);
        //采购的状态，新建状态
        wmsPurchase.setStatus(WmsPurchaseStatus.NEW.getStatus());
        wmsPurchaseMapper.insert(wmsPurchase);
        //2 新建采购单详情
        List<WmsPurchaseDetailAddDTO> wmsPurchaseDetailAddDTOS = wmsPurchaseAddDTO.getWmsPurchaseDetailAddDTOList();
        //3 采购单的总价
        BigDecimal totalPrice=new BigDecimal(0);
        for (WmsPurchaseDetailAddDTO wmsPurchaseDetailAddDTO : wmsPurchaseDetailAddDTOS) {
            WmsPurchaseDetail wmsPurchaseDetail = new WmsPurchaseDetail();
            BeanUtils.copyProperties(wmsPurchaseDetailAddDTO, wmsPurchaseDetail);
            wmsPurchaseDetail.setPurchaseId(wmsPurchase.getId());
            BigDecimal tempPrice=wmsPurchaseDetailAddDTO.getSkuPrice().multiply(new BigDecimal(wmsPurchaseDetailAddDTO.getSkuNum()));
            totalPrice=totalPrice.add(tempPrice);
            wmsPurchaseDetailMapper.insert(wmsPurchaseDetail);
        }
        wmsPurchase.setAmount(totalPrice);
        wmsPurchaseMapper.updateById(wmsPurchase);
        return true;
    }

    @Transactional
    public boolean allocationWmsPurchase(long assigneeId, String assigneeName, String phone, Long id) {
        WmsPurchase wmsPurchase = wmsPurchaseMapper.selectById(id);
        if(wmsPurchase==null){
            throw new HttpException(40001,500);
        }
        wmsPurchase.setAssigneeId(assigneeId);
        wmsPurchase.setAssigneeName(assigneeName);
        wmsPurchase.setPhone(phone);
        wmsPurchase.setStatus(WmsPurchaseStatus.ALLOCATION.getStatus());
        int result=wmsPurchaseMapper.updateById(wmsPurchase);
        if (result>0){
            return true;
        }
        return false;
    }

    @Transactional
    public boolean finishWmsPurchase(long id) {
        //String userId=UserContextHolder.getInstance().getUserId();
        String userId="1";
        WmsPurchase wmsPurchase=wmsPurchaseMapper.selectById(id);
        //采购单状态不是已经分配，此时不能接收采购单
        if (wmsPurchase==null){
            throw new HttpException(40003,500);
        }
        if (wmsPurchase.getStatus()!=WmsPurchaseStatus.SHOPPING.getStatus()){
            throw new HttpException(40006,500);
        }
        String assigneeId=wmsPurchase.getAssigneeId()+"";
        //完成采购人和分配的人不是同一个，不能进行完成操作
        if (!userId.equals(assigneeId)){
            throw new HttpException(40007,500);
        }
        //3 修改采购单的状态
        wmsPurchase.setStatus(WmsPurchaseStatus.FINISH.getStatus());
        wmsPurchaseMapper.updateById(wmsPurchase);
        long wareId=wmsPurchase.getWareId();//采购单对应仓库的id
        // 4 商品入库（查询商品的详情信息，sku进行入库）
        LambdaQueryWrapper<WmsPurchaseDetail> lambdaQueryWrapper= new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmsPurchaseDetail::getPurchaseId,id);
        List<WmsPurchaseDetail> wmsPurchaseDetails=wmsPurchaseDetailMapper.selectList(lambdaQueryWrapper);
        //遍历采购单的详情，将采购单详情入库
        for (WmsPurchaseDetail wmsPurchaseDetail : wmsPurchaseDetails) {
            long skuId=wmsPurchaseDetail.getSkuId();
            int skuNum=wmsPurchaseDetail.getSkuNum();
            //入库的商品原来在仓库中不存在，执行新增
            LambdaQueryWrapper<WmsWareSku> wmsWareSkuLambdaQueryWrapper= new LambdaQueryWrapper<>();
            wmsWareSkuLambdaQueryWrapper.eq(WmsWareSku::getSkuId,skuId);
            wmsWareSkuLambdaQueryWrapper.eq(WmsWareSku::getWareId,wareId);
            int count=wmsWareSkuMapper.selectCount(wmsWareSkuLambdaQueryWrapper);
            if (count==0){
                WmsWareSku wmsWareSku=new WmsWareSku();
                wmsWareSku.setSkuId(skuId);
                wmsWareSku.setWareId(wareId);
                wmsWareSku.setSkuName(wmsPurchaseDetail.getSkuName());
                wmsWareSku.setStock(skuNum);
                wmsWareSku.setStockLocked(0);
                wmsWareSkuMapper.insert(wmsWareSku);
            }else {
                //入库的商品在原来仓库中，执行更新操作
                WmsWareSku wmsWareSku=wmsWareSkuMapper.selectOne(wmsWareSkuLambdaQueryWrapper);
                wmsWareSku.setStock(wmsWareSku.getStock()+skuNum);
                wmsWareSkuMapper.updateById(wmsWareSku);
            }
        }
        return true;
    }
}
